/*
 * Copyright 2008 Robert Hanson <iamroberthanson AT gmail.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.penlets.io;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import com.livescribe.penlet.Penlet;
import com.livescribe.penlet.PenletContext;
import com.livescribe.storage.PenletStorage;

/**
 * Collection of IO utility methods. Because IO functionality
 * requires access to the PenletContext all methods are instance
 * methods and you must construct an instance of IOUtils prior to
 * using it. 
 * @author robert.hanson
 */
public final class IOUtils
{
    
    private PenletContext context;


    /**
     * Build an IOUtils instance from a Penlet.
     * @param penlet a Penlet
     */
    public IOUtils (Penlet penlet)
    {
        this.context = penlet.getContext();
    }

    /**
     * Build an IOUtils instance from a PenletContext.
     * @param context a PenletContext
     */
    public IOUtils (PenletContext context)
    {
        this.context = context;
    }


    /**
     * Reads a file that was bundled in the JAR file, returning
     * it as a String.
     * @param filePath path to the file
     * @return contents of the file as a String
     * @throws IOException
     */
    public String readFileFromJar (String filePath) throws IOException
    {
        StringBuffer result = new StringBuffer();
        InputStream stream = this.getClass().getResourceAsStream(filePath);
        InputStreamReader reader = new InputStreamReader(stream);

        char[] buff = new char[1024];
        int pos = reader.read(buff, 0, 1024);
        while (pos != -1) {
            result.append(buff, 0, pos);
            pos = reader.read(buff, 0, 1024);
        }
        
        return result.toString();
    }

    /**
     * Reads a file that was stored using the internal penlet
     * storage, returning it as a String.
     * @param filePath path to the file
     * @return contents of the file as a String
     * @throws IOException
     */
    public String readFile (String filePath) throws IOException
    {
        StringBuffer result = new StringBuffer();
        PenletStorage ps = context.getInternalPenletStorage();
        InputStream stream = ps.openInputStream(filePath);
        InputStreamReader reader = new InputStreamReader(stream);
        
        char[] buff = new char[1024];
        int pos = reader.read(buff, 0, 1024);
        while (pos != -1) {
            result.append(buff, 0, pos);
            pos = reader.read(buff, 0, 1024);
        }
        
        return result.toString();
    }
    

    /**
     * Writes a String to a file in the internal penlet storage.
     * If the file exists an IOException is thrown.
     * @param filePath path to the file
     * @param data String value to be stored
     * @throws IOException
     */
    public void writeFile (String filePath, String data) throws IOException
    {
        writeFile(filePath, data, false);
    }
    
    
    /**
     * Writes a String to a file in the internal penlet storage.
     * If the overwrite flag is false and the file exists,
     * an IOException is thrown.
     * @param filePath path to the file
     * @param data String value to be stored
     * @param overwrite flag to allow existing file to be overwritten
     * @throws IOException
     */
    public void writeFile (String filePath, String data, boolean overwrite)
            throws IOException
    {
        PenletStorage ps = context.getInternalPenletStorage();
        if (overwrite == false) {
            if (ps.exists(filePath)) {
                throw new IOException("File exists and overwrite flag is false");
            }
        }
        OutputStream out = ps.openOutputStream(filePath, false);
        out.write(data.getBytes());
        out.close();
    }

    /**
     * Appends a String value to the end of a file in the penlet
     * internal storage, creating the file if it does not exist.
     * @param filePath path to the file
     * @param data value to store
     * @throws IOException
     */
    public void appendFile (String filePath, String data) throws IOException
    {
        PenletStorage ps = context.getInternalPenletStorage();
        OutputStream out = ps.openOutputStream(filePath, true);
        out.write(data.getBytes());
        out.close();
    }

}
